var express = require('express');
var router = express.Router();

const formidable = require('formidable')
const moment = require('moment');
const jwt = require('jsonwebtoken');
//导入中间件 
let checkTokenMiddleware = require('../../middlewares/checktoken');
const roleModel = require('../../models/roleModel');
const { default: mongoose } = require('mongoose');
const { render } = require('../../app');
const userModel = require('../../models/userModel');
const accessModel = require('../../models/accessModel');
const subaccModel = require('../../models/subaccountModel');
const path = require('path');
const fs = require('fs')
const {domain,secret} = require('../../config/config');
require('moment-timezone');
moment.tz.setDefault('Asia/Shanghai');
console.log(moment().format('YYYY-MM-DD HH:mm:ss'));

router.get('/getAccessInfo',function(req, res, next) {
    let user = req.session.user
    accessModel.find({user:user})
    .then(data => {
        console.log(data);
      res.json({
        code:'1',
        msg:'success',
        data:data
      })
     
    })
    .catch(err => {
        res.json({
            code:'2',
            msg:'false'
            
          })

    });

});

router.get('/onbingAccess',function(req, res, next) {
    let user = req.session.user
    let sname = req.query.sname
    let access_type = req.query.access_type
    const currentTimeChina = moment().format('YYYY-MM-DD HH:mm:ss');
    subaccModel.findOne ({sname:sname}).then((data)=>{
        if(data){
            accessModel.findOne({user:user,sname:sname,access_type:access_type}).then((data)=>{
                if(data){
                    res.json({
                        code:'1',
                        msg:'账号已经绑定该权限',
                        data:data
                    })
                }else{
                    accessModel.create({
                        user:user,
                        sname:sname,
                        access_type:access_type,
                        last_time:currentTimeChina
                    }).then((data) => {
                        //
                        res.json({
                            code:'1',
                            msg:'绑定成功',
                            data:data
                        })
                        
                    })
                    .catch(err => {
                        res.json({
                            code:'2',
                            msg:'绑定异常'
                            
                        })
                
                
                    });
                }
               
            }).catch(err => {
                res.json({
                    code:'2',
                    msg:'查询失败',
                    
                })
            })
        }else{
            res.json({
                code:'2',
                msg:'子账号不存在',
                
            })
        }
        
    }).catch(err => {
        res.json({
            code:'2',
            msg:'查询账号异常',
            
        })
    })
    
    
});

router.get('/updateSubAccount',function(req, res, next) {

    let user = req.session.user
    let name = req.query.new_account
    let password = req.query.new_password
    console.log(user,name,password)
 
    const currentTimeChina = moment().format('YYYY-MM-DD HH:mm:ss');
    subaccModel.findOne ({sname:name}).then((data)=>{
        if(data){
            subaccModel.updateOne ({sname:name},{ $set:{user:user,password:password,last_time:currentTimeChina}}).then((data)=>{
                console.log(data)
                res.json({
                    code:'1',
                    msg:'修改成功',
                    data:data
                })
            }).catch(err => {
                console.log(err)
                res.json({
                    code:'2',
                    msg:'修改账号信息失败'
                    
                })
            })    
        }else{
            subaccModel.create({
                sname:name,
                password:password,
                user:user,
                last_time:currentTimeChina
            }).then((data) => {
                //
                res.json({
                    code:'1',
                    msg:'创建成功',
                    data:data
                })
                
            })
            .catch(err => {
                res.json({
                    code:'2',
                    msg:'添加失败'
                    
                })
        
        
            });
        }
        
    }).catch(err => {
        res.json({
            code:'2',
            msg:'查询账号异常',
            
        })
    })
   
});
router.get('/getSubAccount',function(req, res, next) {
    let user = req.session.user
    subaccModel.find({user:user})
    .then(data => {
        console.log(data);
        res.json({
            code:'1',
            msg:'success',
            data:data
        })
     
    })
    .catch(err => {
        res.json({
            code:'2',
            msg:'false'
            
          })

    });

});

router.get('/delSubAccount',function(req, res, next) {
    let user = req.session.user
    let id = req.query.id
    console.log(id)
    subaccModel.deleteOne({_id:id})
    .then(data => {
        console.log(data);
        res.json({
            code:'1',
            msg:'success',
            data:data
        })
     
    })
    .catch(err => {
        res.json({
            code:'2',
            msg:'false'
            
          })

    });

});


router.get('/delAccess',function(req, res, next) {
    let user = req.session.user
    let id = req.query.id
    accessModel.deleteOne({_id:id})
    .then(data => {
        console.log(data);
        res.json({
            code:'1',
            msg:'success',
            data:data
        })
     
    })
    .catch(err => {
        res.json({
            code:'2',
            msg:'false'
            
          })

    });

});

router.get('/onChangePassword',function(req, res, next) {

    let user = req.session.user
    let password = req.query.new_password
    console.log(user,password)
    userModel.updateOne ({user:user},{ $set:{password:password}}).then((data)=>{
        console.log(data)
        res.json({
            code:'1',
            msg:'修改成功',
            data:data
        })
    }).catch(err => {
        console.log(err)
        res.json({
            code:'2',
            msg:'修改账号信息失败'
            
        })
    })    
   
});
router.post('/getAccessType',function(req, res, next) {
    console.log(req.body.userName)
    let userName = req.body.userName
    let password = req.body.password
    let access_type=req.body.access_type
    console.log(userName,password,access_type)
    subaccModel.findOne({sname:userName,password:password})
    .then(data => {
        console.log(data);
        if(data){
            accessModel.findOne({sname:userName,access_type:access_type})
            .then(data => {
                console.log(data);
                if(data){
                    res.json({
                        code:'1',
                        msg:'授权成功',
                       
                    })
                }else{
                    res.json({
                        code:'2',
                        msg:'授权失败'
                        
                    })

                }
            
            })
            .catch(err => {
                res.json({
                    code:'2',
                    msg:'登录失败(2)'
                    
                })
        
            });
        }else{
            res.json({
                code:'2',
                msg:'账号密码错误'
                
            })
        }
     
    })
    .catch(err => {
        res.json({
            code:'2',
            msg:'登录失败'
            
        })

    });

});
router.get('/', function(req, res, next) {
  console.log(__dirname);
  res.render('login');
});

/* 远程布局 */
router.post('/uploadPic',(req, res, next) => {
    console.log("uploadPic")
    /* console.log(req) */
const currentTimeChina = moment().format('YYYY-MM-DD HH:mm:ss');
const form = new formidable.IncomingForm({
    multiples:true,
    //设置上传文件的保存目录
    uploadDir: __dirname + "/../../public/hk",
    //保持文件后缀
    keepExtensions: true
    
});

form.parse(req, (err, fields, files) => {
    if (err) {
        console.log(err)
        res.json({code:"2",msg:"上传错误"})
    return;
    }
    try {
        console.log(path.parse(files.file[0].newFilename).name)
        let filesPath = path.resolve(__dirname, '../../public/hk/'+`${path.parse(files.file[0].newFilename).name}.txt`);
        fs.writeFileSync(filesPath, fields.data[0].toString());
        
        res.json({code:"1",msg:"success"})
    } catch (error) {
        if(fs.existsSync(files.file[0].filepath)) {
            fs.unlinkSync(files.file[0].filepath);
        }
      
        res.json({code:"2",msg:"error"})
    }
    
});
});
router.post('/getUIData',(req, res, next) => {
    console.log("getUIData")
const currentTimeChina = moment().format('YYYY-MM-DD HH:mm:ss');

let folder = path.resolve(__dirname, '../../public/hk');
fs.readdir(folder, function(err, files){
    if(err){
        res.json({code:"2",msg:"获取目录文件失败"})
    }
    console.log(files)  
    res.json({code:"1",msg:"success",data:files,Dir:"http://106.53.210.53:4000/hk/"})
});




});
router.post('/delUIData',(req, res, next) => {
    console.log("delUIData")
    try {
        let folder = path.resolve(__dirname, '../../public/hk');
        let flieName = req.body.flieName
        let filepath = folder +"/"+ req.body.flieName + ".jpg"
        if(flieName && fs.existsSync(filepath)) {
            fs.unlinkSync(filepath);
        }
        filepath = folder +"/"+ req.body.flieName + ".txt"
        if(flieName && fs.existsSync(filepath)) {
            fs.unlinkSync(filepath);
        }
        res.json({code:"1",msg:"删除成功"})
    } catch (error) {
        res.json({code:"1",msg:"删除失败"})
        console.log(error)
    }
    

});
/* 服务器部署初始化. */
router.get('/init_db', function(req, res, next) {
    roleModel.findOne({name:"admin"}).then(data=>{
        if(!data){
            roleModel.create({
                name:"admin",
                desc:"管理员权限"
            }).catch(err=>{ console.log(err);
                console.log("创建管理员失败")})
        }
    })
    roleModel.findOne({name:"user"}).then(data=>{
        if(!data){
            roleModel.create({
                name:"user",
                desc:"普通用户权限"
            }).catch(err=>{ console.log("创建普通用户失败")})
        }
    })
    roleModel.findOne({name:"staff"}).then(data=>{
        if(!data){
            roleModel.create({
                name:"staff",
                desc:"员工用户权限"
            }).catch(err=>{ console.log("创建员工用户失败")})
        }
    })
    roleModel.findOne({name:"user"}).then(data=>{
        if(data){
            const userid = data.id
            userModel.find().then(data=>{
                if(data){
                    let user_data = []
                    data.forEach(user=>{
                        if(!user.permissions){
                            user_data.push(user.id)
                           
                        }
                    })
                    console.log(user_data)
                    userModel.updateMany({id:{$in:user_data}},{$set:{permissions:userid,desc:"普通用户"}}).catch(err=>{
                        console.log(err)
                    })
                }
            })
            
            
        }
    })


    res.json({code:0,msg:"success"})
    
    
    
});



//新接口




module.exports = router;
